package com.gt.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gt.utils.DESUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 对返回报文进行des加密
 */
@Slf4j
@RestControllerAdvice
public class PublicEncryptResponseBodyAdvice implements ResponseBodyAdvice {
    private final static Logger logger = LoggerFactory.getLogger(PublicEncryptResponseBodyAdvice.class);
    private String[] includeUrl = new String[]{
            "/public/"
            ,"/manager/favorCoupon"
            ,"/manager/getRecordById"
//            ,"/demo/test"

    };
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        return request.getServletPath().startsWith("/public/") || request.getServletPath().startsWith("/manager/favorCoupon");
        for (String url : includeUrl) {
            if (request.getServletPath().startsWith(url)) {
                return true;
            }
        }
        return false;
    }
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        logger.info("对接口 :{} ，返回数据：{}，进行加密",request.getURI().getPath(), JSON.toJSONString(body, SerializerFeature.WriteMapNullValue));
        try {
            return DESUtil.encrypt(DESUtil.DES_KEY, JSON.toJSONString(body, SerializerFeature.WriteMapNullValue));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return body;
    }
}
